// audioPlayer/index.js
import audioManager from '../../utils/audioManager.js'

Page({
  data: {
    // 音频信息
    audioInfo: {
      id: '',
      title: '未知音频',
      description: '',
      duration: '00:00',
      size: '',
      format: '',
      category: '',
      url: '',
      thumbnail: ''
    },
    
    // 播放状态
    playState: {
      isPlaying: false,
      isPaused: false,
      isLoading: false,
      currentTime: 0,
      totalDuration: 0,
      progress: 0,
      volume: 50,
      playMode: 'list' // list: 列表循环, single: 单曲循环, random: 随机
    },
    
    // 播放列表（可选）
    playlist: [],
    currentIndex: 0,
    
    // UI状态
    showVolumeControl: false,
    showPlaylist: false,
    isDragging: false
  },

  // 音频上下文
  audioContext: null,
  progressTimer: null,

  onLoad(options) {
    // 绑定全局音频管理器事件
    this.bindAudioManagerEvents()
    
    // 获取传递的音频ID
    if (options.audioId) {
      this.loadAudioDetail(options.audioId)
    }
    
    // 获取播放列表（可选）
    if (options.playlist) {
      try {
        const playlist = JSON.parse(decodeURIComponent(options.playlist))
        audioManager.setPlaylist(playlist, parseInt(options.index) || 0)
        this.setData({
          playlist: playlist,
          currentIndex: parseInt(options.index) || 0
        })
      } catch (e) {
        console.error('解析播放列表失败:', e)
      }
    }
    
    // 从全局管理器同步状态
    this.syncFromAudioManager()
    
    // 隐藏浮窗（因为已经在播放页面了）
    audioManager.setFloatingPlayerVisible(false)
  },

  onUnload() {
    // 页面卸载时解绑事件监听
    this.unbindAudioManagerEvents()
    
    // 显示浮窗（如果正在播放）
    const state = audioManager.getState()
    if (state.playState.isPlaying || state.currentAudio.id) {
      audioManager.setFloatingPlayerVisible(true)
    }
  },

  onHide() {
    // 页面隐藏时显示浮窗
    const state = audioManager.getState()
    if (state.playState.isPlaying || state.currentAudio.id) {
      audioManager.setFloatingPlayerVisible(true)
    }
  },

  onShow() {
    // 页面显示时隐藏浮窗
    audioManager.setFloatingPlayerVisible(false)
    
    // 同步状态
    this.syncFromAudioManager()
  },

  /**
   * 绑定音频管理器事件
   */
  bindAudioManagerEvents() {
    // 使用bind保持this指向
    this.boundStateChangeHandler = this.onAudioManagerStateChange.bind(this)
    this.boundAudioChangeHandler = this.onAudioManagerAudioChange.bind(this)
    
    audioManager.addEventListener('stateChange', this.boundStateChangeHandler)
    audioManager.addEventListener('audioChange', this.boundAudioChangeHandler)
  },

  /**
   * 解绑音频管理器事件
   */
  unbindAudioManagerEvents() {
    if (this.boundStateChangeHandler) {
      audioManager.removeEventListener('stateChange', this.boundStateChangeHandler)
    }
    if (this.boundAudioChangeHandler) {
      audioManager.removeEventListener('audioChange', this.boundAudioChangeHandler)
    }
  },

  /**
   * 音频管理器状态变化回调
   */
  onAudioManagerStateChange: function(playState, showFloatingPlayer) {
    this.setData({
      playState: {
        isPlaying: playState.isPlaying,
        isPaused: playState.isPaused,
        isLoading: playState.isLoading,
        currentTime: playState.currentTime,
        totalDuration: playState.totalDuration,
        progress: playState.progress,
        volume: playState.volume,
        playMode: playState.playMode
      }
    })
  },

  /**
   * 音频管理器音频变化回调
   */
  onAudioManagerAudioChange: function(currentAudio) {
    this.setData({
      audioInfo: {
        id: currentAudio.id,
        title: currentAudio.title || '未知音频',
        description: currentAudio.description || '',
        duration: currentAudio.duration || '00:00',
        size: currentAudio.size || '',
        format: currentAudio.format || '',
        category: currentAudio.category || '',
        url: currentAudio.url || '',
        thumbnail: currentAudio.thumbnail || ''
      }
    })
  },

  /**
   * 从音频管理器同步状态
   */
  syncFromAudioManager() {
    const state = audioManager.getState()
    this.onAudioManagerStateChange(state.playState, state.showFloatingPlayer)
    this.onAudioManagerAudioChange(state.currentAudio)
    
    this.setData({
      playlist: state.playlist,
      currentIndex: state.currentIndex
    })
  },

  /**
   * 初始化音频上下文
   */
  initAudioContext() {
    this.audioContext = wx.createInnerAudioContext()
    
    // 播放开始
    this.audioContext.onPlay(() => {
      console.log('音频开始播放')
      this.setData({
        'playState.isPlaying': true,
        'playState.isPaused': false,
        'playState.isLoading': false
      })
      this.startProgressTimer()
    })
    
    // 播放暂停
    this.audioContext.onPause(() => {
      console.log('音频暂停')
      this.setData({
        'playState.isPlaying': false,
        'playState.isPaused': true
      })
      this.stopProgressTimer()
    })
    
    // 播放停止
    this.audioContext.onStop(() => {
      console.log('音频停止')
      this.setData({
        'playState.isPlaying': false,
        'playState.isPaused': false,
        'playState.currentTime': 0,
        'playState.progress': 0
      })
      this.stopProgressTimer()
    })
    
    // 播放结束
    this.audioContext.onEnded(() => {
      console.log('音频播放结束')
      this.handlePlayEnd()
    })
    
    // 播放错误
    this.audioContext.onError((res) => {
      console.error('音频播放错误:', res)
      this.setData({
        'playState.isLoading': false,
        'playState.isPlaying': false
      })
      wx.showToast({
        title: '播放失败',
        icon: 'none'
      })
    })
    
    // 音频加载中
    this.audioContext.onWaiting(() => {
      this.setData({
        'playState.isLoading': true
      })
    })
    
    // 音频可以播放
    this.audioContext.onCanplay(() => {
      this.setData({
        'playState.isLoading': false,
        'playState.totalDuration': this.audioContext.duration || 0
      })
    })
  },

  /**
   * 销毁音频上下文
   */
  destroyAudioContext() {
    if (this.audioContext) {
      this.audioContext.destroy()
      this.audioContext = null
    }
    this.stopProgressTimer()
  },

  /**
   * 加载音频详情
   */
  loadAudioDetail(audioId) {
    wx.showLoading({
      title: '加载中...'
    })

    wx.cloud.callFunction({
      name: 'fetchAudio',
      data: {
        type: 'getAudioDetail',
        audioId: audioId
      }
    }).then(res => {
      wx.hideLoading()
      
      if (res.result && res.result.success) {
        const audioDetail = res.result.data
        this.setData({
          audioInfo: {
            id: audioDetail._id,
            title: audioDetail.title || '未知音频',
            description: audioDetail.description || '',
            duration: audioDetail.duration || '00:00',
            size: audioDetail.size || '',
            format: audioDetail.format || '',
            category: audioDetail.category || '',
            url: audioDetail.url || '',
            thumbnail: audioDetail.thumbnail || ''
          }
        })
        
        // 设置到全局管理器
        audioManager.setCurrentAudio({
          id: audioDetail._id,
          title: audioDetail.title || '未知音频',
          description: audioDetail.description || '',
          duration: audioDetail.duration || '00:00',
          size: audioDetail.size || '',
          format: audioDetail.format || '',
          category: audioDetail.category || '',
          url: audioDetail.url || '',
          thumbnail: audioDetail.thumbnail || ''
        })
      } else {
        wx.showToast({
          title: '加载音频失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.hideLoading()
      console.error('获取音频详情失败:', err)
      wx.showToast({
        title: '网络请求失败',
        icon: 'none'
      })
    })
  },

  /**
   * 播放/暂停切换
   */
  togglePlay() {
    const success = audioManager.togglePlay()
    if (!success) {
      wx.showToast({
        title: '音频文件不存在',
        icon: 'none'
      })
    }
  },

  /**
   * 上一首
   */
  playPrevious() {
    audioManager.playPrevious()
  },

  /**
   * 下一首
   */
  playNext() {
    audioManager.playNext()
  },

  /**
   * 根据索引播放音频
   */
  playAudioByIndex(index) {
    const { playlist } = this.data
    if (index >= 0 && index < playlist.length) {
      this.setData({
        currentIndex: index
      })
      this.loadAudioDetail(playlist[index]._id)
    }
  },

  /**
   * 处理播放结束
   */
  handlePlayEnd() {
    const { playMode, playlist, currentIndex } = this.data
    
    switch (playMode) {
      case 'single':
        // 单曲循环
        this.audioContext.seek(0)
        this.audioContext.play()
        break
      case 'list':
        // 列表循环
        if (playlist.length > 0) {
          this.playNext()
        }
        break
      case 'random':
        // 随机播放
        if (playlist.length > 0) {
          const randomIndex = Math.floor(Math.random() * playlist.length)
          this.playAudioByIndex(randomIndex)
        }
        break
    }
  },

  /**
   * 切换播放模式
   */
  togglePlayMode() {
    const modes = ['list', 'single', 'random']
    const currentMode = this.data.playState.playMode
    const currentIndex = modes.indexOf(currentMode)
    const nextMode = modes[(currentIndex + 1) % modes.length]
    
    audioManager.setPlayMode(nextMode)
    
    const modeNames = {
      list: '列表循环',
      single: '单曲循环',
      random: '随机播放'
    }
    
    wx.showToast({
      title: modeNames[nextMode],
      icon: 'none',
      duration: 1000
    })
  },

  /**
   * 进度条拖拽开始
   */
  onProgressStart() {
    this.setData({
      isDragging: true
    })
    this.stopProgressTimer()
  },

  /**
   * 进度条拖拽中
   */
  onProgressChange(e) {
    if (!this.data.isDragging) return
    
    const progress = e.detail.value
    const currentTime = (progress / 100) * this.data.playState.totalDuration
    
    this.setData({
      'playState.progress': progress,
      'playState.currentTime': currentTime
    })
  },

  /**
   * 进度条拖拽结束
   */
  onProgressEnd(e) {
    const progress = e.detail.value
    audioManager.seekTo(progress)
    
    this.setData({
      isDragging: false
    })
  },

  /**
   * 音量控制
   */
  onVolumeChange(e) {
    const volume = e.detail.value
    audioManager.setVolume(volume)
  },

  /**
   * 切换音量控制显示
   */
  toggleVolumeControl() {
    this.setData({
      showVolumeControl: !this.data.showVolumeControl,
      showPlaylist: false // 关闭播放列表
    })
  },

  /**
   * 关闭音量控制
   */
  closeVolumeControl() {
    this.setData({
      showVolumeControl: false
    })
  },

  /**
   * 切换播放列表显示
   */
  togglePlaylist() {
    this.setData({
      showPlaylist: !this.data.showPlaylist,
      showVolumeControl: false // 关闭音量控制
    })
  },

  /**
   * 关闭播放列表
   */
  closePlaylist() {
    this.setData({
      showPlaylist: false
    })
  },

  /**
   * 清空播放列表
   */
  clearPlaylist() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空播放列表吗？',
      success: (res) => {
        if (res.confirm) {
          audioManager.clearPlaylist()
          wx.showToast({
            title: '已清空播放列表',
            icon: 'success'
          })
        }
      }
    })
  },

  /**
   * 点击播放列表项
   */
  onPlaylistItemTap(e) {
    const { index } = e.currentTarget.dataset
    audioManager.playAudioByIndex(parseInt(index))
    
    // 关闭播放列表
    this.setData({
      showPlaylist: false
    })
  },

  /**
   * 从播放列表移除
   */
  removeFromPlaylist(e) {
    const { index } = e.currentTarget.dataset
    const removeIndex = parseInt(index)
    
    wx.showModal({
      title: '确认移除',
      content: '确定要从播放列表中移除这首音频吗？',
      success: (res) => {
        if (res.confirm) {
          const success = audioManager.removeFromPlaylist(removeIndex)
          
          if (success) {
            wx.showToast({
              title: '已移除',
              icon: 'success'
            })
          }
        }
      }
    })
  },

  /**
   * 阻止事件冒泡
   */
  preventBubble() {
    // 阻止点击事件冒泡
  },

  /**
   * 开始进度计时器
   */
  startProgressTimer() {
    this.stopProgressTimer()
    this.progressTimer = setInterval(() => {
      if (this.audioContext && this.data.playState.isPlaying && !this.data.isDragging) {
        const currentTime = this.audioContext.currentTime
        const totalDuration = this.audioContext.duration || this.data.playState.totalDuration
        const progress = totalDuration > 0 ? (currentTime / totalDuration) * 100 : 0
        
        this.setData({
          'playState.currentTime': currentTime,
          'playState.totalDuration': totalDuration,
          'playState.progress': progress
        })
      }
    }, 1000)
  },

  /**
   * 停止进度计时器
   */
  stopProgressTimer() {
    if (this.progressTimer) {
      clearInterval(this.progressTimer)
      this.progressTimer = null
    }
  },

  /**
   * 格式化时间
   */
  formatTime(seconds) {
    if (!seconds || isNaN(seconds)) return '00:00'
    
    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
})
